package com.honeywen.mymvc.leetcode;

/**
 * @author wangwei
 * @date 2019/8/5
 */
public class InsertionSortList {

    public static void main(String[] args) {

        ListNode n1 = new ListNode(4);
        ListNode n2 = new ListNode(2);
        ListNode n3 = new ListNode(1);
        ListNode n4 = new ListNode(3);
        n1.next = n2;
        n2.next = n3;
        n3.next = n4;


        // -1->5->3->4->0
        ListNode node1 = new ListNode(-1);
        ListNode node2 = new ListNode(5);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(0);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;



        n1.print();
        insertionSortList(n1).print();

        System.out.println("------------");
        node1.print();
        insertionSortList(node1).print();

    }


    public static ListNode insertionSortList(ListNode head) {

        if (head == null || head.next == null) {
            return head;
        }

        ListNode node = head;
        ListNode start = head;
        ListNode prev = node;
        node = node.next;
        while (node != null) {

            if (prev.val > node.val) {
                // 翻转往前，直到遇到合适位置

                ListNode tmp = start;
                while (tmp != node) {
                    if (node.val < tmp.val) {

                        tmp.next = node.next;
                        node.next = tmp;

                        if (tmp == start) {
                            head = node;
                        }

                    }

                    tmp = tmp.next;
                }


            }
            prev = node;
            node = node.next;
        }


        return head;


    }
}
